package com.nettm.leetcode;

import java.util.ArrayList;
import java.util.List;

public class MergeTwoSortedLists021 {

    public static void main(String[] args) {
        MergeTwoSortedLists021 m = new MergeTwoSortedLists021();
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(7);
        l1.next.next = new ListNode(9);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(5);
        l2.next.next.next = new ListNode(8);

        ListNode lst = m.mergeTwoLists(l1, l2);
        System.out.println(lst.val);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        List<ListNode> lst = new ArrayList<>();
        if (l1 == null && l2 != null) {
            return l2;
        } else if (l1 != null && l2 == null) {
            return l1;
        } else if (l1 == null && l2 == null) {
            return null;
        } else {
            ListNode result = null;
            while (l1 != null || l2 != null) {
                ListNode tmp = null;
                if (l1 != null && l2 != null) {
                    if (l1.val < l2.val) {
                        tmp = new ListNode(l1.val);
                        l1 = l1.next;
                    } else {
                        tmp = new ListNode(l2.val);
                        l2 = l2.next;
                    }
                } else if (l1 != null && l2 == null) {
                    tmp = new ListNode(l1.val);
                    l1 = l1.next;
                } else if (l1 == null && l2 != null) {
                    tmp = new ListNode(l2.val);
                    l2 = l2.next;
                }
                lst.add(tmp);
            }

            result = lst.get(0);
            int length = lst.size();
            for (int i = 1; i < length; i++) {
                lst.get(i - 1).next = lst.get(i);
            }

            return result;
        }
    }
}
